import time
import datetime
import configparser
import sys
from PySide6.QtCore import QCoreApplication, QObject, QThread, Signal
from PySide6.QtCore import QSettings
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
from Global import mo
import requests




def Goto_CurrentActivateUrl(driver: WebDriver) -> None:
    """使用 requests 获取当前激活的页面的 url,并切换到当前激活的页面.

    Args:
        driver (WebDriver): WebDriver 实例

    Returns:
        _type_: None
    """
    debug_json_data = requests.get(
        url="http://127.0.0.1:9652/json", timeout=5).json()

    # 判断获取回来的数据是否正确
    if not isinstance(debug_json_data, list):
        print("接口返回数据格式不正确（非列表或为空）")
        return None

    # 过来掉不需要的 page 页面
    filter_json_data = list(
        filter(lambda item:      item['type'] == "page" or
               item['title'].lower().startswith("devtools") or
               item['title'].lower().startswith("offscreen") or
               item['url'].lower().startswith("chrome-extension") or
               item['url'].lower().startswith("chrome-devtools") or
               item['url'].lower().startswith("chrome-extension"), debug_json_data)
    )
    current_activate_handle = filter_json_data[0]['id']
    driver.switch_to.window(current_activate_handle)




if __name__ == "__main__":
    mo.start_time = datetime.datetime.now()
    print("程序开始时间 : ",mo.start_time)
    
    
    app = QCoreApplication(sys.argv)


    # 读取配置信息
    settings = QSettings("config.ini", QSettings.IniFormat)
    localtion = settings.value("path/host",type=str)
    port = settings.value("path/port",type=int)
    
    
    # 加载驱动远程链接调试浏览器    
    options = Options()
    service = Service()
    options.add_experimental_option("debuggerAddress", f"{localtion}:{port}")
    driver = WebDriver(options=options)
    actions = ActionChains(driver=driver)
    # driver.implicitly_wait(10)  # 隐式等待，当页面元素不存在时，等待10秒，如果存在就继续执行
    wait = WebDriverWait(driver=driver,timeout=10)
    
    
    # 打印当前注入 JavaScript 脚本文件的页面地址
    Goto_CurrentActivateUrl(driver=driver)
    print(f"Current Url is : {driver.current_url}")


    # 加载JavaScript脚本文件到浏览器中去
    with open(file="./res/script.js",mode="r",encoding="utf-8") as f:
        scripttext = f.read()
        driver.execute_script(script=scripttext)
        print(f"当前 js 脚本文件执行完毕.")


    print("Main thread is exiting.")
    mo.end_time = datetime.datetime.now()
    print("程序结束时间 : ",mo.end_time)
    print("程序运行时间 : ",mo.end_time-mo.start_time)